package com.sasis.webapp.listener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sasis.webapp.task.ScheduleTask;
import com.sasis.webapp.task.ScheduleRunner;
import com.sasis.webapp.task.StartupTask;
import com.sasis.webapp.task.TaskManager;
import com.sasis.webapp.task.TaskThread;

public class TaskListener implements ServletContextListener {
	
	private Timer timer;
	
	public void contextInitialized(ServletContextEvent sce) {
		timer= new Timer(true);
		executeTasks(sce.getServletContext());
	}

	public void contextDestroyed(ServletContextEvent sce) {
		timer.cancel();
	}
	
	private void executeTasks(ServletContext context) {
		try {
			TaskManager taskManager = (TaskManager) WebApplicationContextUtils
					.getRequiredWebApplicationContext(context).getBean("taskManager");
			
			List startupTasks = taskManager.getStartupTasks();
			executeStartupTasks(startupTasks, context);
			startupTasks.clear();
			startupTasks = null;
			
			List scheduleTasks = taskManager.getScheduleTasks();
			executeScheduleTasks(scheduleTasks, context);
			scheduleTasks.clear();
			scheduleTasks = null;
		}catch (Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void executeStartupTasks(List startupTasks, ServletContext context) {
		if (startupTasks == null || startupTasks.size() == 0) {
			return ;
		}
		List asynchTasks = new ArrayList();
		for (Iterator iterator = startupTasks.iterator(); iterator.hasNext(); ) {
			StartupTask startupTask = (StartupTask) iterator.next();
			if (startupTask.isAsynchronous()) {
				asynchTasks.add(startupTask);
			} else {
				startupTask.doTask(context);
			}
		}
		if (asynchTasks.size() > 0) {
			new TaskThread(asynchTasks, context).start();
		}
	}
	
	private void executeScheduleTasks(List scheduleTasks, ServletContext context) {
		if (scheduleTasks == null || scheduleTasks.size() == 0) {
			return ;
		}
		for (Iterator iterator = scheduleTasks.iterator(); iterator.hasNext(); ) {
			ScheduleTask scheduleTask = (ScheduleTask) iterator.next();
			timer.schedule(new ScheduleRunner(scheduleTask, context), scheduleTask.getScheduleTime());
		}
	}

}
